package sendtemplateinterfacelogic

import (
	"context"
	"errors"
	"fmt"

	"dfx_cmdb/cmdb-sendmsg-rpc/internal/svc"
	cmdb_database_sync "dfx_cmdb/cmdb-sendmsg-rpc/types/cmdb-database-sync"
	"dfx_cmdb/models"
	cmdbsendmsg "dfx_cmdb/models/cmdb-sendmsg"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdateSendTemplateLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUpdateSendTemplateLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateSendTemplateLogic {
	return &UpdateSendTemplateLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// UpdateSendTemplate 更新指定的发送模板
func (l *UpdateSendTemplateLogic) UpdateSendTemplate(in *cmdb_database_sync.SendTemplateInfo) (*cmdb_database_sync.PublicMsgResponse, error) {
	// todo: add your logic here and delete this line
	if in.Id == 0 {
		return &cmdb_database_sync.PublicMsgResponse{
			Msg: "更新发送模板失败，ID不能为空",
		}, errors.New("ID不能为空")
	}

	var sendTemplate []cmdbsendmsg.SendTemplate
	if err := l.svcCtx.DB.Model(&cmdbsendmsg.SendTemplate{}).Where("id = ?", in.Id).Find(&sendTemplate).Error; err != nil {
		return &cmdb_database_sync.PublicMsgResponse{
			Msg: "查询发送模板失败",
		}, err
	}

	if len(sendTemplate) == 0 {
		return &cmdb_database_sync.PublicMsgResponse{
			Msg: "发送模板不存在",
		}, fmt.Errorf("发送模板不存在")
	}

	sendTemplate[0].TemplateName = in.TemplateName
	sendTemplate[0].TemplateMsg = in.TemplateMsg

	if err := models.UpdateDatabase(l.svcCtx.DB, sendTemplate[0], map[string]interface{}{"id": in.Id}); err != nil {
		return &cmdb_database_sync.PublicMsgResponse{
			Msg: "更新发送模板失败",
		}, err
	}
	logx.Infof("更新数据成功，更新%v条数据", len(sendTemplate))

	return &cmdb_database_sync.PublicMsgResponse{
		Msg: fmt.Sprintf("更新发送模板成功，更新%v条数据", len(sendTemplate)),
	}, nil
}
